<template>
  <div class="filter-card">
    <div class="filter-actions-row">
      <el-checkbox v-model="myOnly" @change="handleMyOnlyChange">
        我的任务
      </el-checkbox>
      <div class="filter-actions">
        <el-button type="primary" @click="handleSearch">搜索</el-button>
        <el-button @click="handleReset">重置</el-button>
      </div>
    </div>

    <div class="filter-search-row">
      <el-input
        v-model="localFilters.search"
        placeholder="搜索任务标题、描述、编号..."
        clearable
        class="filter-search"
        @keyup.enter="handleSearch"
      >
        <template #prefix>
          <el-icon><Search /></el-icon>
        </template>
      </el-input>
    </div>

    <div class="filter-item">
      <label>版本</label>
      <el-select
        v-model="localFilters.version_id"
        placeholder="请选择版本"
        filterable
        clearable
        @change="handleImmediateChange"
      >
        <el-option
          v-for="version in filteredVersions"
          :key="version.id"
          :label="`${version.version_number} - ${version.name}`"
          :value="version.id"
        />
      </el-select>
    </div>

    <div class="filter-item">
      <label>任务状态</label>
      <el-select
        v-model="localFilters.status"
        placeholder="请选择状态"
        clearable
        @change="handleImmediateChange"
      >
        <el-option
          v-for="option in statusOptions"
          :key="option.value"
          :label="option.label"
          :value="option.value"
        />
      </el-select>
    </div>

    <div class="filter-item">
      <label>优先级</label>
      <el-select
        v-model="localFilters.priority"
        placeholder="请选择优先级"
        clearable
        @change="handleImmediateChange"
      >
        <el-option
          v-for="option in priorityOptions"
          :key="option.value"
          :label="option.label"
          :value="option.value"
        />
      </el-select>
    </div>

    <div class="filter-item">
      <label>负责人</label>
      <el-select
        v-model="localFilters.assignee_id"
        placeholder="请选择负责人"
        clearable
        filterable
        @change="handleImmediateChange"
      >
        <el-option
          v-for="user in users"
          :key="user.id"
          :label="user.name || user.username"
          :value="user.id"
        >
          <UserDisplay
            :user="user"
            :show-avatar="true"
            size="small"
          />
        </el-option>
      </el-select>
    </div>

    <div class="filter-item">
      <label>截止日期</label>
      <el-date-picker
        v-model="dueDateRange"
        type="daterange"
        range-separator="至"
        start-placeholder="开始日期"
        end-placeholder="结束日期"
        format="YYYY-MM-DD"
        value-format="YYYY-MM-DD"
        unlink-panels
        style="width: 100%"
        @change="handleDateRangeChange"
      />
    </div>
  </div>
</template>

<script setup lang="ts">
import { reactive, ref, watch, computed } from 'vue'
import { Search } from '@element-plus/icons-vue'
import type { ProjectResponse } from '@/api/project'
import type { User } from '@/types/user'
import type { VersionWithStats } from '@/api/version'
import UserDisplay from '@/components/ui/UserDisplay.vue'

interface TaskFilters {
  search?: string
  project_id?: string
  version_id?: string
  status?: string
  priority?: string
  assignee_id?: string
  due_date_from?: string
  due_date_to?: string
}

const props = defineProps<{
  filters: TaskFilters
  projects: ProjectResponse[]
  users: User[]
  versions: VersionWithStats[]
  statusOptions: Array<{ value: string; label: string }>
  priorityOptions: Array<{ value: string; label: string }>
  currentUserId?: string
  selectedProjectId?: string
}>()

const emit = defineEmits<{
  (event: 'apply', filters: Partial<TaskFilters>): void
  (event: 'reset'): void
}>()

const localFilters = reactive<TaskFilters>({ ...props.filters })
const dueDateRange = ref<[string, string] | []>([])
const myOnly = ref(false)

const filteredVersions = computed(() => {
  if (!props.selectedProjectId) {
    return props.versions
  }
  return props.versions.filter(v => v.project_id === props.selectedProjectId)
})

watch(
  () => props.filters,
  value => {
    // 使用 Object.assign 更新所有字段，确保同步
    Object.keys(localFilters).forEach(key => {
      if (key in value) {
        const newValue = value[key as keyof TaskFilters]
        const currentValue = (localFilters as any)[key]
        // 只有当值真正改变时才更新，避免触发循环更新
        if (newValue !== currentValue) {
          (localFilters as any)[key] = newValue
        }
      }
    })
    // 处理日期范围
    if (value.due_date_from && value.due_date_to) {
      const newRange: [string, string] = [value.due_date_from, value.due_date_to]
      // 只有当日期范围真正改变时才更新
      if (dueDateRange.value.length !== 2 || 
          dueDateRange.value[0] !== newRange[0] || 
          dueDateRange.value[1] !== newRange[1]) {
        dueDateRange.value = newRange
      }
    } else {
      if (dueDateRange.value.length > 0) {
        dueDateRange.value = []
      }
    }
    // 更新"我的任务"复选框状态
    const newMyOnly = Boolean(props.currentUserId && value.assignee_id === props.currentUserId)
    if (myOnly.value !== newMyOnly) {
      myOnly.value = newMyOnly
    }
  },
  { deep: true, immediate: true }
)

watch(
  () => props.selectedProjectId,
  () => {
    // 当项目变化时，清空版本选择
    if (!props.selectedProjectId) {
      localFilters.version_id = undefined
    }
  }
)

const handleSearch = () => {
  emit('apply', { ...localFilters })
}

const handleReset = () => {
  // 重置本地筛选条件
  Object.assign(localFilters, {
    search: undefined,
    project_id: undefined,
    version_id: undefined,
    status: undefined,
    priority: undefined,
    assignee_id: undefined,
    due_date_from: undefined,
    due_date_to: undefined
  })
  dueDateRange.value = []
  myOnly.value = false
  emit('reset')
}

const handleImmediateChange = () => {
  // 当负责人选择改变时，同步更新"我的任务"复选框状态
  if (props.currentUserId) {
    myOnly.value = localFilters.assignee_id === props.currentUserId
  } else {
    myOnly.value = false
  }
  emit('apply', { ...localFilters })
}

const handleMyOnlyChange = (val: boolean | string | number) => {
  const checked = Boolean(val)
  // 检查 currentUserId 是否存在且不为空字符串
  if (checked && props.currentUserId && typeof props.currentUserId === 'string' && props.currentUserId.trim() !== '') {
    // 勾选"我的任务"时，设置负责人为当前用户
    localFilters.assignee_id = props.currentUserId
    // 立即触发筛选，确保筛选条件被应用
    emit('apply', { 
      ...localFilters,
      assignee_id: props.currentUserId 
    })
  } else {
    // 取消勾选"我的任务"时，清空负责人筛选
    localFilters.assignee_id = undefined
    // 立即触发筛选，确保筛选条件被清除
    emit('apply', { 
      ...localFilters,
      assignee_id: undefined 
    })
  }
}

const handleDateRangeChange = (value: [string, string] | []) => {
  if (Array.isArray(value) && value.length === 2) {
    localFilters.due_date_from = value[0]
    localFilters.due_date_to = value[1]
  } else {
    localFilters.due_date_from = undefined
    localFilters.due_date_to = undefined
  }
  emit('apply', { ...localFilters })
}
</script>

<style scoped lang="scss">
.filter-card {
  display: flex;
  flex-direction: column;
  gap: 16px;
  padding: 20px;
  background: #ffffff;
  border-radius: 12px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
  border: 1px solid #ebeef5;
}

.filter-actions-row {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding-bottom: 12px;
  border-bottom: 1px solid #f0f2f5;
  margin-bottom: 4px;
}

.filter-actions {
  display: flex;
  gap: 8px;
  
  :deep(.el-button) {
    padding: 6px 12px;
    border-radius: 6px;
    font-weight: 500;
    font-size: 13px;
    transition: all 0.2s;
    
    &:hover {
      transform: translateY(-1px);
      box-shadow: 0 2px 8px rgba(64, 158, 255, 0.2);
    }
  }
}

.filter-search-row {
  display: flex;
  margin-bottom: 4px;
  
  :deep(.el-input) {
    .el-input__wrapper {
      border-radius: 8px;
      box-shadow: 0 0 0 1px #dcdfe6 inset;
      transition: all 0.2s;
      
      &:hover {
        box-shadow: 0 0 0 1px #c0c4cc inset;
      }
      
      &.is-focus {
        box-shadow: 0 0 0 1px #409eff inset;
      }
    }
  }
}

.filter-search {
  flex: 1;
}

.filter-item {
  display: flex;
  flex-direction: column;
  gap: 8px;
  
  label {
    font-size: 13px;
    color: #606266;
    font-weight: 500;
    margin-bottom: 2px;
  }
  
  :deep(.el-select),
  :deep(.el-date-editor) {
    width: 100%;
    
    .el-input__wrapper {
      border-radius: 6px;
      transition: all 0.2s;
      
      &:hover {
        box-shadow: 0 0 0 1px #c0c4cc inset;
      }
      
      &.is-focus {
        box-shadow: 0 0 0 1px #409eff inset;
      }
    }
  }
  
  :deep(.el-checkbox) {
    .el-checkbox__label {
      font-size: 13px;
      color: #606266;
      font-weight: 500;
    }
  }
}

:deep(.el-checkbox) {
  .el-checkbox__input {
    .el-checkbox__inner {
      border-radius: 4px;
      transition: all 0.2s;
    }
  }
  
  &:hover .el-checkbox__inner {
    border-color: #409eff;
  }
}
</style>

